package com.framemodule.utils;

import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.OnScrollListener;
import android.view.View;


/**
 * Created by kangjie on 2017/8/5.
 */

public class ScrollListener4ControlView extends OnScrollListener {
    private View topView;
    private RecyclerView mRecyclerView;
    private int topViewHeight;

    /**
     *
     * @param topView           需要控制的标题栏
     * @param topViewHeightPX   标题栏高度
     * @param recyclerView      监听的recylerView
     */
    public ScrollListener4ControlView(View topView, int topViewHeightPX, RecyclerView recyclerView){
        this.topView = topView;
        this.mRecyclerView = recyclerView;
        topViewHeight = topViewHeightPX;
    }
    
    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        if (newState==RecyclerView.SCROLL_STATE_IDLE){
            moveRecyleview();
        }

    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
            setTopViewY(dy);
    }

    public void setTopViewY(int dy) {
        if (topView.getY()>(-topViewHeight-1)&&topView.getY()<1){
            int y = (int) (topView.getY()-dy);
            if (y>0){
                topView.setY(0);
            }else if (y<-topViewHeight){
                topView.setY(-topViewHeight);
            }else {
                topView.setY(topView.getY()-dy);
            }

        }else {
            if (topView.getY()>0){
                topView.setY(0);
            }else if (topView.getY()<-topViewHeight){
                topView.setY(-topViewHeight);
            }
        }

    }

    public void moveRecyleview() {
        if (topView.getY()==0||topView.getY()==(int) -(topView.getY()-(-topViewHeight))){
            return;
        }
        if (topView.getY()>-topViewHeight/2){
            mRecyclerView.smoothScrollBy(0, (int) (topView.getY()));
        }else {
            mRecyclerView.smoothScrollBy(0, (int) (topView.getY()-(-topViewHeight)));
        }

    }
    
    
}
